package com.bclz.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioThreadPoolServer {


    private BioThreadPoolServer(){

    }

    public static BioThreadPoolServer  build(int port, ExecutorService executor) throws IOException {

        ServerSocket serverSocket=new ServerSocket(port);
        while (true){
            Socket socket = serverSocket.accept();
            executor.execute(()->{
                System.out.println("creating socket Thread :"+Thread.currentThread().getId());
                try {
                    handle(socket);
                }catch (IOException e){
                    System.out.println("SOCKET ERROR!!!!"+e);
                }finally {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("SOCKET ERROR!!!!"+e);
                    }
                }


            });

        }



    }

    public static void handle(Socket socket) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
        String line;
        while(( line=bufferedReader.readLine())!=null){
            System.out.println(Thread.currentThread().getId()+" accept msg "+line);
        }
    }

    public static void main(String[] args) throws IOException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        BioThreadPoolServer.build(6666, executorService);
    }

}
